package com.hnust.service.impl;

import com.hnust.api.PersonalDataApis;
import com.hnust.api.TeacherApis;
import com.hnust.controller.MainController;
import com.hnust.controller.personInfo.PersonDataController;
import com.hnust.domain.*;
import com.hnust.fx.DialogBuilder;
import com.hnust.service.PersonalDataServices;
import com.hnust.store.DataStore;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXPasswordField;
import io.datafx.core.concurrent.ProcessChain;
import javafx.collections.FXCollections;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PersonalDataServicesImpl implements PersonalDataServices {
    @Autowired
    private PersonalDataApis personalDataApis;
    @Autowired
    private TeacherApis teacherApis;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private MainController mainController;
    @Autowired
    private PersonDataController personDataController;

    private static final Logger logger = LogManager.getLogger(PersonalDataServicesImpl.class);

    @Override
    public void getTeacherInfo(VBox loadingInfo, GridPane teacherInfoContainer, JFXButton teacherInfoBtn,
                               String teacher_id, Label selectCollege, TextField teacherNumber,
                               TextField teacherName, TextField teacherPhone, TextField teacherMail,
                               JFXPasswordField teacherPassword, ComboBox<College> college) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            loadingInfo.setVisible(true);loadingInfo.setManaged(true);
            teacherInfoContainer.setVisible(false);teacherInfoContainer.setManaged(false);
            teacherInfoBtn.setVisible(false);teacherInfoBtn.setManaged(false);
        }).addSupplierInExecutor(()-> personalDataApis.getInfo(teacher_id))
                .addConsumerInPlatformThread((result)->{
                    UserInfo userInfo=result.getData();
                    teacherNumber.setText(userInfo.getFaculty_number());
                    teacherName.setText(userInfo.getName());
                    teacherPhone.setText(userInfo.getPhone());
                    teacherMail.setText(userInfo.getEmail());
                    teacherPassword.setText(userInfo.getPassword());
                    loadingInfo.setVisible(false);loadingInfo.setManaged(false);
                    teacherInfoContainer.setVisible(true);teacherInfoContainer.setManaged(true);
                    teacherInfoBtn.setVisible(true);teacherInfoBtn.setManaged(true);
                    getCollege(userInfo.getCollegeId(),selectCollege,college);
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(teacherInfoBtn).setTitle("提示").setMessage("网络出错，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).run();
    }

    private void getCollege(String collegeId, Label selectCollege, ComboBox<College> college) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            selectCollege.setText("正在获取学院列表...");
        }).addSupplierInExecutor(()-> teacherApis.getAllCollege())
                .addConsumerInPlatformThread((result)->{
                    List<College> colleges=result.getData();
                    logger.info("选中的学院ID："+collegeId);
                    logger.info("获取的学院列表："+colleges);
                    int index=0;
                    for(int i=0;i<colleges.size();i++){
                        if(colleges.get(i).getColId().equals(collegeId)){
                            index=i;
                            break;
                        }
                    }
                    college.setItems(FXCollections.observableArrayList(colleges));
                    college.getSelectionModel().select(index);
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(selectCollege).setTitle("提示").setMessage("网络出错，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            selectCollege.setText("学院:");
        }).run();
    }

    @Override
    public void modifyTeacherInfo(String number, String name, String phone,
                                  String mail, String password, String selectCollegeId,
                                  JFXButton teacherInfoBtn) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            teacherInfoBtn.setText("更新中...");
            teacherInfoBtn.setDisable(true);
        }).addSupplierInExecutor(()-> personalDataApis.updateUserInfo(new UpdateInfoReqBody(
                new UpdateUserInfo(name,phone,mail,number,selectCollegeId,password),
                dataStore.getToken(),dataStore.getTeacher_id()
        ))).addConsumerInPlatformThread((result)->{
            if(result.getCode()==1){
                new DialogBuilder(teacherInfoBtn).setTitle("提示").setMessage("更新信息成功").
                    setPositiveBtn("确定","#3333cc").create();
                mainController.teacherName.setText(name);
                dataStore.setTeacher_name(name);
            }else{
                new DialogBuilder(teacherInfoBtn).setTitle("提示").setMessage("更新信息失败").
                    setPositiveBtn("确定","#ff3333").create();
            }
        }).onException(e->{
            e.printStackTrace();
            new DialogBuilder(teacherInfoBtn).setTitle("提示").setMessage("网络异常，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            teacherInfoBtn.setDisable(false);
            teacherInfoBtn.setText("更新信息");
        }).run();
    }

    @Override
    public void getCourseGroupData(JFXListView<StackPane> courseGroup, String college_id,
                                   String teacher_id, VBox loadingCourseGroup) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            courseGroup.setVisible(false);courseGroup.setManaged(false);
            loadingCourseGroup.setVisible(true);loadingCourseGroup.setManaged(true);
        }).addSupplierInExecutor(()->{
            List<CourseGroup> entered=new ArrayList<>();
            Result<UserInfo> teacherInfo=personalDataApis.getInfo(teacher_id);
            if(teacherInfo.getData()!=null){
                for(GroupInfo i:teacherInfo.getData().getGroup()){
                    entered.add(new CourseGroup(i.getId(),i.getName(),1));
                }
            }
            Result<List<GroupInfo>> waitGroupInfos=personalDataApis.getWaitCourseGroup(teacher_id);
            if(waitGroupInfos.getData()!=null){
                for(GroupInfo i:waitGroupInfos.getData()){
                    entered.add(new CourseGroup(i.getId(),i.getName(),3));
                }
            }
            Result<List<GroupInfo>> allGroupInfos=personalDataApis.getCourseGroup(college_id);
            if(allGroupInfos.getData()!=null){
                for(GroupInfo i:allGroupInfos.getData()){
                    boolean flag=false;
                    for(CourseGroup k:entered){
                        if(i.getId().equals(k.getId())){
                            flag=true;
                            break;
                        }
                    }
                    if(!flag){
                        entered.add(new CourseGroup(i.getId(),i.getName(),2));
                    }
                }
            }
            return entered;
        }).addConsumerInPlatformThread((result)->{
            logger.info("课程组获取之后的处理结果:"+result);
            List<StackPane> panes=new ArrayList<>();
            if(result.size()!=0){
                for(CourseGroup i:result){
                    StackPane s=new StackPane();s.getStyleClass().add("courseGroupItem");
                    Label l1=new Label(i.getId());l1.setVisible(false);l1.setManaged(false);
                    Label l2=new Label(i.getName());l2.getStyleClass().add("label_text");
                    HBox h=new HBox();h.setAlignment(Pos.CENTER_RIGHT);
                    Label l3=new Label(i.getType()==1?"已加入":i.getType()==2?"未加入":"待审核");
                    l3.getStyleClass().add("label_text");
                    if(i.getType()==1)
                        l3.getStyleClass().add("enter_text");
                    if(i.getType()==3)
                        l3.getStyleClass().add("audit_text");
                    h.getChildren().add(l3);
                    s.getChildren().addAll(l1,l2,h);
                    panes.add(s);
                }
                courseGroup.setItems(FXCollections.observableList(panes));
                courseGroup.setVisible(true);courseGroup.setManaged(true);
                loadingCourseGroup.setVisible(false);loadingCourseGroup.setManaged(false);
            }
        }).onException(e->{
            e.printStackTrace();
            new DialogBuilder(courseGroup).setTitle("提示").setMessage("网络错误，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).run();
    }

    @Override
    public void exitCourseGroup(JFXButton exitCourseGroupBtn, String selectCourseGroupId) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            exitCourseGroupBtn.setText("退出中...");
            exitCourseGroupBtn.setDisable(true);
        }).addSupplierInExecutor(()-> personalDataApis.outCourse(dataStore.getTeacher_id(),selectCourseGroupId))
                .addConsumerInPlatformThread((result)->{
                    if(result.getCode()==1){
                        new DialogBuilder(exitCourseGroupBtn).setTitle("提示").setMessage("退出成功").
                                setPositiveBtn("确定","#3333cc").create();
                        personDataController.getCourseGroupData();
                    }else{
                        new DialogBuilder(exitCourseGroupBtn).setTitle("提示").setMessage("退出失败").
                                setPositiveBtn("确定","#ff3333").create();
                    }
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(exitCourseGroupBtn).setTitle("提示").setMessage("网络错误，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            exitCourseGroupBtn.setText("退出");
            exitCourseGroupBtn.setDisable(false);
        }).run();
    }

    @Override
    public void joinCourseGroup(JFXButton joinCourseGroupBtn, String selectCourseGroupId) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            joinCourseGroupBtn.setText("加入中...");
            joinCourseGroupBtn.setDisable(true);
        }).addSupplierInExecutor(()-> personalDataApis.applyCourseGroup(dataStore.getTeacher_id(),selectCourseGroupId))
                .addConsumerInPlatformThread((result)->{
                    if(result.getCode()==1){
                        new DialogBuilder(joinCourseGroupBtn).setTitle("提示").setMessage("申请加入成功,请等待管理员审核").
                                setPositiveBtn("确定","#3333cc").create();
                        personDataController.getCourseGroupData();
                    }else{
                        new DialogBuilder(joinCourseGroupBtn).setTitle("提示").setMessage("申请加入失败").
                                setPositiveBtn("确定","#ff3333").create();
                    }
                }).onException(e->{
            e.printStackTrace();
            new DialogBuilder(joinCourseGroupBtn).setTitle("提示").setMessage("网络错误，请稍后再试").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            joinCourseGroupBtn.setText("申请加入");
            joinCourseGroupBtn.setDisable(false);
        }).run();
    }
}
